package com.diapoc.diorsgallery.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.Environment;
import android.os.Message;
import android.util.Log;

public abstract class DownloadManager {

	public Bitmap byte2Bitmap(byte[] data) {
		Options options = new Options();
		options.inSampleSize = 3;
		Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
				options);
		return bitmap;
	}

	public ByteArrayOutputStream download(String url) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		ByteArrayOutputStream outstream = null;
		try {
			myFileUrl = new URL(url);
		} catch (MalformedURLException e) {
			LogManager.show(e.toString());
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			long time = System.currentTimeMillis();
			InputStream is = conn.getInputStream();
			LogManager.show("getInputStream的时间："
					+ (System.currentTimeMillis() - time) + "     "
					+ is.toString());
			int len;
			int size = conn.getContentLength();
			byte buffer[] = new byte[1024 * 4];
			int index = 0;
			int hasRead = 0;
			outstream = new ByteArrayOutputStream();
			while ((len = is.read(buffer)) != -1) {
				outstream.write(buffer, 0, len);
				hasRead += len;
				index = (int) (hasRead * 100) / size;
				LogManager.show("index = " + index);
				LogManager.show("has = " + hasRead + " size = " + size
						+ " index = " + index);
				onDownLoading(index);
			}

			// bitmap = BitmapFactory.decodeStream(is);
			is.close();
			outstream.close();
		} catch (IOException e) {
			LogManager.show(e.toString());
		}
		return outstream;
	}

	abstract public void onDownLoading(int rate);
}
